﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Manage_EditArticle : System.Web.UI.Page
{
    protected List<Annex> annexes = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            #region 加载Templates下面的模版
            string path = Server.MapPath("~/Templates");
            var fs = from aF in (new DirectoryInfo(path)).GetFiles("*.aspx")
                     where !aF.Name.StartsWith("_")
                     select new { Name = aF.Name.Replace(".aspx", "") };
            ArticleTemplates.DataSource = fs.ToList();
            ArticleTemplates.DataValueField = "Name";
            ArticleTemplates.DataTextField = "Name";
            ArticleTemplates.DataBind();

            ArticleTemplates.Items[0].Selected = true;
            #endregion


            string id = Request.Params["aid"];
            if (id != null)
            {
                CmsDataContext db = new CmsDataContext();
                Article article = (from aA in db.Article
                                   where aA.ID == id
                                   select aA).First();
                #region 加载文章信息
                ArticleID.Value = article.ID;
                ArticleTitle.Text = article.Title;
                ArticleSubtitle.Text = article.Subtitle;
                ArticleKeywords.Text = article.Keywords;
                ArticleBody.Text = article.Body;
                ArticleFooter.Text = article.Footer;

                if (article.TopicID != null)
                {
                    TopicID.Value = article.TopicID;
                    TopicName.InnerText = article.Topic.Name;
                }

                annexes = article.Annex.ToList();

                ArticleTemplates.SelectedValue = article.Template;
                #endregion

                #region 当前用户是否是文章的作者，文章是否通过审核
                //SelectAnnex.Visible = (article.CreatorID == Toolkit.CurrentUserID) && (article.Verified == null);
                //SelectParent.Visible = (article.CreatorID == Toolkit.CurrentUserID) && (article.Verified == null);
                //Save.Visible = (article.CreatorID == Toolkit.CurrentUserID) && (article.Verified == null);
                #endregion

                #region 如果是文章审核员，则显示审核按钮
                //VerifyArticle.Visible = (article.Verified == null) && Toolkit.HasPower(Powers.ArticleVerifier);
                //NoReply.Visible = (article.Verified == null) && Toolkit.HasPower(Powers.ArticleVerifier);

                //if (NoReply.Visible)
                //{
                //    NoReply.HRef = "./NoVerifyArticle.aspx?aid=" + article.ID;
                //}
                #endregion
            }
        }
    }
    protected void Save_Click(object sender, EventArgs e)
    {
        CmsDataContext db = new CmsDataContext();
        string id = ArticleID.Value.Trim();
        Article article;

        try
        {
            if (id == "")
            {
                article = new Article();
                article.ID = Toolkit.NextUUID;
                article.Clicked = 0;
                article.District = Toolkit.CurrentUserDistrict;
                article.Belong = Toolkit.CurrentUserBelong;
                article.Published = DateTime.Now;
                article.Thumbnail = "";

                article.VerifyID = Toolkit.CurrentUserID;
                article.Verified = DateTime.Now;
                
                db.Article.InsertOnSubmit(article);
            }
            else
            {
                article = (from aA in db.Article
                           where aA.ID == id
                           select aA).First();
            }

            article.Title = ArticleTitle.Text.Trim();
            article.Subtitle = ArticleSubtitle.Text.Trim() != "" ? ArticleSubtitle.Text.Trim() : article.Title;
            article.Keywords = ArticleKeywords.Text.Trim();
            article.TopicID = TopicID.Value.Trim();
            article.Body = ArticleBody.Text.Trim();
            article.Footer = ArticleFooter.Text.Trim();
            article.Template = ArticleTemplates.SelectedValue;

            DateTime dt = article.Published;
            int year = dt.Year;
            int month = dt.Month;

            article.Url = string.Format("{0}/{1}/{2}.html", year, month, article.ID);

            if (article.CreatorID == null)
            {
                article.CreatorID = Convert.ToString(Session["ManagerID"]);
            }

            string aid = AnnexID.Value.Trim();
            if (aid != "")
            {
                string[] ids = aid.Split('|');

                #region 将aid中没有的附件删除
                var q = from aA in db.Annex
                        where !ids.Contains(aA.ID) && aA.ArticleID == article.ID
                        select aA;
                foreach (string url in q.Select(aA => aA.Url))
                {
                    if (File.Exists(string.Format("{0}/{1}", Server.MapPath(Toolkit.PathOfUpload), url)))
                    {
                        File.Delete(string.Format("{0}/{1}", Server.MapPath(Toolkit.PathOfUpload), url));
                    }
                }

                db.Annex.DeleteAllOnSubmit(q);
                #endregion

                #region 选出文章的附件
                q = from aA in db.Annex
                    where ids.Contains(aA.ID)
                    select aA;

                foreach (Annex a in q)
                {
                    a.ArticleID = article.ID;
                }
                #endregion
            }

            db.SubmitChanges();

            Toolkit.StaticArticle(article.Url, article.Template);

            MessageBox.Message = "文章信息保存成功。";
            MessageBox.Location = "./EditArticle.aspx?aid=" + article.ID;
        }
        catch (Exception ee)
        {
            MessageBox.Message = ee.Message;
        }
    }
    protected void VerifyArticle_Click(object sender, EventArgs e)
    {
        CmsDataContext db = new CmsDataContext();

        try
        {
            Article article = (from aA in db.Article
                               where aA.ID == ArticleID.Value.Trim()
                               select aA).First();

            article.VerifyID = Toolkit.CurrentUserID;
            article.Verified = DateTime.Now;

            db.SubmitChanges();

            MessageBox.Message = "文章已经通过审核。";
            MessageBox.Location = "./EditArticle.aspx?aid=" + article.ID;
        }
        catch (Exception ee)
        {
            MessageBox.Message = ee.Message;
        }
    }
}